import { SystemService } from '@service/system.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
	selector: 'app-system-user-edit',
	templateUrl: './system-user-edit.component.html',
	styleUrls: ['./system-user-edit.component.less']
})

export class SystemUserEditComponent extends AbsFormUtil implements OnInit {
	@Input() id: string;
	roleOptions = [];
	userSys = null;
	constructor(
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalRef: NzModalRef,
		private systemService: SystemService
	) {
		super();
	}

	ngOnInit() {
		this.buildForm();
		// if (this.item) {
		// 	this.item.password = null;
		// 	this.validateForm.patchValue(this.item);
		// }
		if (this.id) {
			this.getUserInfo();
			return;
		}
		this.getRoleList();
		this.getFormControl('checkPassword').setValidators(Validators.required)
	}
	private async getUserInfo() {
		const result = await this.systemService.getUserInfo(this.id);
		console.log(result);
		this.getFormControl('password').setValidators(null);
		const roleList = result.roleList.map(it => {
			return {
				label: it.roleName,
				value: it.id,
				checked: !!it.ischeck
			}
		});
		const sysUser = result.sysUser;
		sysUser.psw = sysUser.password;
		delete sysUser.password;
		this.validateForm.patchValue({
			...sysUser,
			roleList
		});
	}
	private async getRoleList() {
		const result = await this.systemService.getRoleList({page:1, limit:1000});
		const roleOptions = result.list.map(it => {
			return {
				label: it.roleName,
				value: it.id,
				checked: false
			}
		});
		this.validateForm.controls.roleList.setValue(roleOptions);
		
	}
	buildForm() {

		this.validateForm = this.fb.group({
			loginName: ['', Validators.required],
			userName: ['', Validators.required],
			password: ['', Validators.required],
			checkPassword: ['', [ this.confirmationValidator]],
			mobile: [''],
			roleList: [[], this.roleValidator],
		});
	}
	confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
		if (!control.value) {
			// return { required: true };
		} else if (control.value !== this.validateForm.controls.password.value) {
			return { confirm: true, error: true };
		}
		return {};
	};
	roleValidator = (control: FormControl): { [s: string]: boolean } => {
		if (!control.value.some(it => it.checked)) {
			return { required: true };
		}
		return {};
	};
	updateConfirmValidator(): void {
		Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
	}


	onSubmit() {
		this.markAsDirty();
		if (!this.validateForm.valid) {
			console.log(this.validateForm);
			return;
		}
		return this.validateForm.value;
	}
	destroyModal() {
		this.nzModalRef.destroy();
	}
}
